package cn.wolfcode.p2p.website.web.interceptor;

import cn.wolfcode.p2p.base.anno.RequiredLogin;
import cn.wolfcode.p2p.base.util.LoginInfoContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckLoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        // 判断是否为动态资源
        if (handler instanceof HandlerMethod){
            // 当前请求的的controller方法对象
            HandlerMethod hm = (HandlerMethod) handler;
            // 判断是否贴有 RequiredLogin 注解
            RequiredLogin requiredLogin = hm.getMethodAnnotation(RequiredLogin.class);
            if (requiredLogin != null && LoginInfoContext.getCurrentLoginInfo() == null){
                // 判断是否登录
                // 重定向到登录页面
                response.sendRedirect("/login.html");
                return false;
            }

        }
        return true;
    }
}
